//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from 'react';
import s from './infoCount.module.less';
import memberIcon from '@/assets/allIcon/icon-member.png';
import { useStores } from '@/hooks';
import UserPhoto from '@/components/Portrait/UserPhoto';
import { observer } from 'mobx-react';
import { Button, Descriptions, Popover, Space, Switch, message } from 'antd';
import { request } from '@/utils/request';
import { useHistory } from 'react-router-dom';
import { APP_ORG_MANAGER_PATH, APP_PROJECT_MANAGER_PATH, GROW_CENTER_PATH } from '@/utils/constant';
import { list_ssh_key_name } from '@/api/local_repo';
import SshKeyListModal from './SshKeyListModal';
import { type FeatureInfo, update_feature, USER_TYPE_ATOM_GIT, USER_TYPE_GIT_CODE, USER_TYPE_GITEE, USER_TYPE_INTERNAL } from '@/api/user';
import { EditOutlined, PlusSquareTwoTone, ReloadOutlined } from '@ant-design/icons';
import { get_my_todo_status } from '@/api/project_issue';
import { count_todo } from '@/api/user_todo';
import { emit, listen } from '@tauri-apps/api/event';
import type * as NoticeType from '@/api/notice_type';
import { appWindow, WebviewWindow } from '@tauri-apps/api/window';
import { list_my_issue as list_my_atomgit_issue } from "@/api/atomgit/issue";
import { list_my_issue as list_my_gitcode_issue } from "@/api/gitcode/issue";
import { list_my_issue as list_my_gitee_issue } from "@/api/gitee/issue";
import type { LearnState } from "@/api/roadmap_user";
import { get_learn_state } from "@/api/roadmap_user";
import { useTranslation } from "react-i18next";

const InfoCount = () => {
  const history = useHistory();

  const { t } = useTranslation();

  const userStore = useStores('userStore');
  const projectStore = useStores('projectStore');
  const orgStore = useStores('orgStore');
  const appStore = useStores('appStore');

  const [sshKeyCount, setSshKeyCount] = useState(0);
  const [showSshKeyModal, setShowSshKeyModal] = useState(false);
  const [userTodoCount, setUserTodoCount] = useState(0);
  const [issueTodoCount, setIssueTodoCount] = useState(0);
  const [gitTodoCount, setGitTodoCount] = useState(0);
  const [learnState, setLearnState] = useState<LearnState | null>(null);

  const loadSshKeyCount = async () => {
    const sshKeyNameList = await list_ssh_key_name();
    setSshKeyCount(sshKeyNameList.length);
  };

  const loadUserTodoCount = async () => {
    if (userStore.sessionId == "" || appStore.vendorCfg == undefined) {
      return;
    }
    if (appStore.vendorCfg.work_bench.enable_user_todo) {
      const res = await request(count_todo({ session_id: userStore.sessionId }));
      setUserTodoCount(res.total_count - res.done_count);
    } else {
      setUserTodoCount(0);
    }
  };

  const loadIssueTodoCount = async () => {
    if (userStore.sessionId == "" || appStore.vendorCfg == undefined) {
      return;
    }
    if (appStore.vendorCfg.ability.enable_project == true && userStore.userInfo.featureInfo.enable_project == true) {
      const res = await request(get_my_todo_status({ session_id: userStore.sessionId }));
      setIssueTodoCount(res.total_count);
    } else {
      setIssueTodoCount(0);
    }
  };

  const loadGitTodoCount = async (showMsg: boolean) => {
    if (userStore.sessionId == "" || userStore.userInfo.userType == USER_TYPE_INTERNAL) {
      return;
    }
    if (userStore.userInfo.userType == USER_TYPE_ATOM_GIT) {
      const tmpList = await list_my_atomgit_issue(userStore.userInfo.extraToken, {
        sort: "updated",
        direction: "desc",
        page: 1,
        per_page: 100,
      });
      setGitTodoCount(tmpList.length);
    } else if (userStore.userInfo.userType == USER_TYPE_GIT_CODE) {
      const tmpList = await list_my_gitcode_issue(userStore.userInfo.extraToken);
      setGitTodoCount(tmpList.length);
    } else if (userStore.userInfo.userType == USER_TYPE_GITEE) {
      const tmpList = await list_my_gitee_issue(userStore.userInfo.extraToken);
      setGitTodoCount(tmpList.length);
    }
    if (showMsg) {
      message.info("刷新Git待办")
    }
  };

  const loadLearnState = async () => {
    const res = await request(get_learn_state({ session_id: userStore.sessionId }));
    setLearnState(res.learn_state);
  };

  const openUserTodoPage = async () => {
    if (userStore.sessionId == "" || appStore.vendorCfg == undefined) {
      return;
    }
    let userFlag = false;
    let issueFlag = false;
    if (appStore.vendorCfg.work_bench.enable_user_todo) {
      userFlag = true;
    }
    if (appStore.vendorCfg.ability.enable_project == true && userStore.userInfo.featureInfo.enable_project == true) {
      issueFlag = true;
    }

    const label = "usertodo";
    const window = WebviewWindow.getByLabel(label);
    if (window != null) {
      return;
    }
    const pos = await appWindow.innerPosition();
    new WebviewWindow(label, {
      url: `user_todo.html?userFlag=${userFlag}&issueFlag=${issueFlag}&userType=${userStore.userInfo.userType}&userToken=${userStore.userInfo.extraToken}`,
      x: pos.x + Math.floor(Math.random() * 200),
      y: pos.y + Math.floor(Math.random() * 200),
      width: 400,
      minWidth: 400,
      maxWidth: 400,
      height: 400,
      minHeight: 400,
      maxHeight: 900,
      alwaysOnTop: true,
      decorations: false,
      transparent: true,
    });
  };

  useEffect(() => {
    loadSshKeyCount();
  }, []);

  useEffect(() => {
    if (userStore.sessionId != "" && appStore.vendorCfg !== undefined) {
      loadUserTodoCount();
    }
  }, [userStore.sessionId, appStore.vendorCfg]);

  useEffect(() => {
    if (userStore.sessionId != "" && appStore.vendorCfg !== undefined) {
      loadIssueTodoCount();
    }
  }, [userStore.sessionId, appStore.vendorCfg, userStore.userInfo.featureInfo.enable_project]);

  useEffect(() => {
    if (userStore.sessionId != "" && userStore.userInfo.userType != USER_TYPE_INTERNAL) {
      loadGitTodoCount(false);
    }
  }, [userStore.sessionId, userStore.userInfo.userType]);

  useEffect(() => {
    if (userStore.sessionId != "" && appStore.vendorCfg?.ability.enable_grow_center) {
      loadLearnState();
    }
  }, [userStore.sessionId, appStore.vendorCfg]);

  useEffect(() => {
    const unListenFn = listen<NoticeType.AllNotice>("notice", ev => {
      const notice = ev.payload;
      if ((notice.IssueNotice?.NewIssueNotice != undefined) || (notice.IssueNotice?.UpdateIssueNotice != undefined) || (notice.IssueNotice?.RemoveIssueNotice != undefined)) {
        loadIssueTodoCount();
      } else if (notice.ClientNotice?.UserTodoChangeNotice != undefined) {
        loadUserTodoCount();
      } else if (notice.ClientNotice?.GitTodoCountNotice != undefined) {
        setGitTodoCount(notice.ClientNotice.GitTodoCountNotice.count);
      }
    });
    return () => {
      unListenFn.then((unListen) => unListen());
    };
  }, [userStore.sessionId]);

  return (
    <div className={s.infoCount_wrap}>
      {(appStore.vendorCfg?.account.inner_account == false && appStore.vendorCfg?.account.external_account == false) && (<div className={s.left_wrap} />)}
      {(appStore.vendorCfg?.account.inner_account == false && appStore.vendorCfg?.account.external_account == false) == false && (
        <div className={s.left_wrap}>
          <div style={{ cursor: (userStore.userInfo.testAccount || userStore.userInfo.userType != USER_TYPE_INTERNAL || userStore.sessionId == "") ? "default" : "pointer" }}
            onClick={e => {
              e.stopPropagation();
              e.preventDefault();
              if (userStore.sessionId == "") {
                return;
              }
              if (userStore.userInfo.testAccount) {
                return;
              }
              if (userStore.userInfo.userType != USER_TYPE_INTERNAL) {
                return;
              }
              userStore.showChangeLogo = true;
              userStore.accountsModal = false;
            }}>
            <UserPhoto logoUri={userStore.userInfo.logoUri} width='60px' style={{ border: "1px solid white", borderRadius: "30px", marginRight: "14px" }} />
          </div>
          <div className={s.content}>
            {userStore.sessionId != "" && (
              <div className={s.name}>
                {t("workbench.top.welcome")}！{userStore.userInfo.displayName}
                {((userStore.userInfo.userType == USER_TYPE_INTERNAL && userStore.userInfo.testAccount == false) || (appStore.vendorCfg?.work_bench.enable_user_resume && userStore.userInfo.testAccount == false)) && (
                  <Button type="link" icon={<EditOutlined />} style={{ minWidth: 0, padding: "0px 0px", height: "20px" }}
                    onClick={e => {
                      e.stopPropagation();
                      e.preventDefault();
                      userStore.showChangeResume = true;
                    }} />
                )}
              </div>
            )}
            <div
              className={s.account}
            >
              {userStore.sessionId != "" && (
                <img src={memberIcon} alt="" />
              )}
              {userStore.sessionId == "" ? (
                <Button type="primary"
                  onClick={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    userStore.showUserLogin = true;
                  }}>{t("workbench.top.login")}</Button>
              ) : (
                <Space style={{ paddingLeft: "2px" }}>
                  {userStore.userInfo.testAccount == false && userStore.userInfo.userType == USER_TYPE_INTERNAL && (
                    <a onClick={e => {
                      e.stopPropagation();
                      e.preventDefault();
                      userStore.showChangePasswd = true;
                      userStore.accountsModal = false;
                    }}>{t("workbench.top.changePassword")}</a>
                  )}
                  <a style={{ fontSize: "12px" }} onClick={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    if (appStore.inEdit) {
                      message.info("请先保存修改内容");
                      return;
                    }
                    userStore.showLogout = true;
                    userStore.accountsModal = false;
                  }}>{t("workbench.top.logout")}</a>
                </Space>
              )}
            </div>
          </div>
        </div>
      )}

      <div className={s.right_wrap}>

        <div className={s.item}>
          <div>{t("workbench.top.sshkeys")}</div>
          <div>
            <Button type='link' style={{ minWidth: 0, padding: "0px 0px", fontSize: "20px", lineHeight: "28px" }}
              onClick={e => {
                e.stopPropagation();
                e.preventDefault();
                setShowSshKeyModal(true);
              }}>
              {sshKeyCount}
            </Button>
          </div>
        </div>

        {userStore.sessionId != "" && ((appStore.vendorCfg?.ability.enable_project == true && userStore.userInfo.featureInfo.enable_project == true) ||
          (appStore.vendorCfg?.work_bench.enable_user_todo == true) || (userStore.userInfo.userType != USER_TYPE_INTERNAL)) && (
            <div className={s.item}>
              <div>{t("workbench.top.todos")}</div>
              <div>
                <Space size="small" style={{ gap: "0px" }}>
                  <Popover placement='bottom' trigger="hover" content={
                    <Space direction='vertical'>
                      {(userStore.sessionId != "" && appStore.vendorCfg != undefined && appStore.vendorCfg.work_bench.enable_user_todo) && (
                        <span>{t("text.userTodos")}&nbsp;{userTodoCount}</span>
                      )}
                      {(userStore.sessionId != "" && appStore.vendorCfg != undefined && appStore.vendorCfg.ability.enable_project == true && userStore.userInfo.featureInfo.enable_project == true) && (
                        <span>{t("text.projectTodos")}&nbsp;{issueTodoCount}</span>
                      )}
                      {(userStore.sessionId != "" && userStore.userInfo.userType != USER_TYPE_INTERNAL) && (
                        <span>{t("text.gitTodos")}&nbsp;{gitTodoCount}</span>
                      )}
                    </Space>
                  }>
                    <Button type='link' style={{ minWidth: 0, padding: "0px 0px", fontSize: "20px", lineHeight: "28px" }}
                      onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        openUserTodoPage();
                      }}>
                      {userTodoCount + issueTodoCount + gitTodoCount}
                    </Button>
                  </Popover>
                  {userStore.userInfo.userType != USER_TYPE_INTERNAL && (
                    <Button type='link' icon={<ReloadOutlined style={{ fontSize: "14px", paddingTop: "4px" }} />} style={{ minWidth: "0px", padding: "0px 0px" }}
                      title="刷新Git待办"
                      onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        loadGitTodoCount(true);
                      }} />
                  )}
                </Space>
              </div>
            </div>
          )}

        {userStore.sessionId != "" && appStore.vendorCfg?.ability.enable_dataview && (
          <div className={s.item}>
            <div>{t("workbench.top.dataview")}</div>
            <div>
              <Switch size='small' checked={userStore.userInfo.featureInfo.enable_data_view} onChange={value => {
                const feature: FeatureInfo = {
                  enable_project: userStore.userInfo.featureInfo.enable_project,
                  enable_org: userStore.userInfo.featureInfo.enable_org,
                  enable_data_view: value,
                  enable_grow_center: userStore.userInfo.featureInfo.enable_grow_center,
                };
                request(update_feature({
                  session_id: userStore.sessionId,
                  feature: feature,
                })).then(() => userStore.updateFeature(feature));
              }} style={{ marginTop: "10px" }} />
            </div>
          </div>
        )}

        {userStore.sessionId != "" && appStore.vendorCfg?.ability.enable_project && (
          <div className={s.item}>
            <div>{t("workbench.top.projects")}</div>
            <div>
              <Space>
                <Button type='link' style={{ minWidth: 0, padding: "0px 0px", fontSize: "20px", lineHeight: "28px" }}
                  onClick={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    history.push(APP_PROJECT_MANAGER_PATH);
                  }} disabled={!userStore.userInfo.featureInfo.enable_project}>
                  {projectStore.projectList.filter((item) => !item.closed).length}/{projectStore.projectList.length}
                </Button>
                <Switch size='small' checked={userStore.userInfo.featureInfo.enable_project} onChange={value => {
                  const feature: FeatureInfo = {
                    enable_project: value,
                    enable_org: userStore.userInfo.featureInfo.enable_org,
                    enable_data_view: userStore.userInfo.featureInfo.enable_data_view,
                    enable_grow_center: userStore.userInfo.featureInfo.enable_grow_center,
                  };
                  request(update_feature({
                    session_id: userStore.sessionId,
                    feature: feature,
                  })).then(() => userStore.updateFeature(feature));

                  const notice: NoticeType.AllNotice = {
                    ClientNotice: {
                      TodoConfigChangeNotice: {
                        userFlag: appStore.vendorCfg?.work_bench.enable_user_todo ?? false,
                        issueFlag: (appStore.vendorCfg?.ability.enable_project == true && value == true)
                      },
                    },
                  };
                  emit("notice", notice);
                }} />
              </Space>
            </div>
          </div>
        )}

        {userStore.sessionId != "" && appStore.vendorCfg?.ability.enable_org && (
          <div className={s.item}>
            <div>{t("workbench.top.orgs")}</div>
            <div>
              <Space>
                <Button type='link' style={{ minWidth: 0, padding: "0px 0px", fontSize: "20px", lineHeight: "28px" }}
                  onClick={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    history.push(APP_ORG_MANAGER_PATH);
                  }} disabled={!userStore.userInfo.featureInfo.enable_org}>
                  {orgStore.orgList.length}
                </Button>
                <Switch size='small' checked={userStore.userInfo.featureInfo.enable_org} onChange={value => {
                  const feature: FeatureInfo = {
                    enable_project: userStore.userInfo.featureInfo.enable_project,
                    enable_org: value,
                    enable_data_view: userStore.userInfo.featureInfo.enable_data_view,
                    enable_grow_center: userStore.userInfo.featureInfo.enable_grow_center,
                  };
                  request(update_feature({
                    session_id: userStore.sessionId,
                    feature: feature,
                  })).then(() => userStore.updateFeature(feature));
                }} />
              </Space>
            </div>
          </div>
        )}

        {userStore.sessionId != "" && appStore.vendorCfg?.ability.enable_grow_center && (
          <div className={s.item}>
            <div>{t("workbench.top.growcenter")}</div>
            <div>
              <Space>
                <Button type='link' style={{ minWidth: 0, padding: "0px 0px", fontSize: "20px", lineHeight: "28px" }}
                  onClick={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    history.push(GROW_CENTER_PATH);
                  }} disabled={!userStore.userInfo.featureInfo.enable_grow_center}>
                  <Popover trigger="hover" placement='bottom' content={
                    <Descriptions bordered column={1}>
                      <Descriptions.Item label="最近访问">{learnState?.access_record_count ?? 0}</Descriptions.Item>
                      <Descriptions.Item label="学习阶段">{learnState?.done_topic_count ?? 0}/{learnState?.total_topic_count ?? 0}</Descriptions.Item>
                      <Descriptions.Item label="知识点">{learnState?.done_sub_topic_count ?? 0}/{learnState?.total_sub_topic_count ?? 0}</Descriptions.Item>
                    </Descriptions>
                  }>
                    {(learnState?.done_topic_count ?? 0) + (learnState?.done_sub_topic_count ?? 0)}
                  </Popover>
                </Button>
                <Switch size='small' checked={userStore.userInfo.featureInfo.enable_grow_center} onChange={value => {
                  const feature: FeatureInfo = {
                    enable_project: userStore.userInfo.featureInfo.enable_project,
                    enable_org: userStore.userInfo.featureInfo.enable_org,
                    enable_data_view: userStore.userInfo.featureInfo.enable_data_view,
                    enable_grow_center: value,
                  };
                  request(update_feature({
                    session_id: userStore.sessionId,
                    feature: feature,
                  })).then(() => userStore.updateFeature(feature));
                }} />
              </Space>
            </div>
          </div>
        )}

        {userStore.sessionId != "" && (appStore.vendorCfg?.ability.enable_project || appStore.vendorCfg?.ability.enable_org) && (
          <div className={s.item}>
            <div>
              {(appStore.vendorCfg?.ability.enable_project && appStore.vendorCfg?.ability.enable_org) && t("workbench.top.joinAll")}
              {(appStore.vendorCfg?.ability.enable_project && appStore.vendorCfg?.ability.enable_org == false) && t("workbench.top.joinProject")}
              {(appStore.vendorCfg?.ability.enable_project == false && appStore.vendorCfg?.ability.enable_org) && t("workbench.top.joinOrg")}
            </div>
            <Button type="link" style={{ minWidth: 0, padding: "0px 0px", fontSize: "20px", lineHeight: "28px" }}
              icon={<PlusSquareTwoTone style={{ fontSize: "20px", paddingTop: "4px" }} twoToneColor={["orange", "#eee"]} />}
              onClick={e => {
                e.stopPropagation();
                e.preventDefault();
                appStore.showJoinModal = true;
              }} />
          </div>
        )}
      </div>


      {showSshKeyModal == true && (
        <SshKeyListModal onCount={value => setSshKeyCount(value)} onClose={() => setShowSshKeyModal(false)} />
      )}
    </div>
  );
};

export default observer(InfoCount);
